//
//  ComposeViewController.swift
//  SinaWeiBo
//
//  Created by dengchen on 15/11/18.
//  Copyright © 2015年 name. All rights reserved.
//
import SVProgressHUD
import SnapKit
import UIKit

class ComposeViewController: UIViewController {

    
    //MARK:响应事件
    
    @objc private func selectPicture() {
        print("selectPicture")
    }
    
    
    @objc private func close() {
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    @objc private func send() {
        
        let urlString = "2/statuses/update.json"
        
        guard let token = UserAccountOAuthModel.shared.Account?.access_token else {
            SVProgressHUD.showErrorWithStatus("客官,您还未登陆哦噢噢噢")
            return
        }
        
        let parmaters = ["access_token": token,"status": textView.text]
        
        NetWorkTool.shared.requestData("POST", URLString: urlString, parameters: parmaters, success: { (result) -> Void in
//                print(result)
            SVProgressHUD.showSuccessWithStatus("发布成功")
            self.close()
            
            }) { (error) -> Void in
                print(error)
        }
        
        
    }
    

    
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    
    @objc private func keyboardWillChange(notify:NSNotification) {
        
        print(notify.userInfo)
        
       let duration = (notify.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! Double)
       let FrameEnd = (notify.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()
        
        let offset = -DcScreenheight + FrameEnd.origin.y
        
        toolbar.snp_updateConstraints { (make) -> Void in
            make.bottom.equalTo(self.view).offset(offset)
        }
        
        UIView.animateWithDuration(duration) { () -> Void in
            self.view.layoutIfNeeded()
        }
        
    }
    
    
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setUpUI()
        
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillChange:", name: UIKeyboardWillChangeFrameNotification, object: nil)
    }
    
    
    
    
    
    
    
    
    
    //MARK:CreatSubView
    
    
    private let textView:UITextView = {
        let tv = UITextView()
        tv.font = UIFont.systemFontOfSize(20)
        tv.textColor = UIColor(white: 0.3, alpha: 1)
 
        return tv
        }()
    
    private let placeHolderLabel = UILabel(title: "分享新鲜事...", Color: UIColor.lightGrayColor(), fontSize: 18, textAlignment: NSTextAlignment.Left)

    private let toolbar = UIToolbar()
    
    
}

//MARK:setUpUI
    
extension ComposeViewController : UITextViewDelegate {
    
    private func setUpUI() {
        view.backgroundColor = UIColor.whiteColor()
        
        setNavBar()
        
        setTextView()
        
        setToolbar()
        
    }
    

    private func setNavBar() {
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: "close")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发布", style: .Plain, target: self, action: "send")
        navigationItem.rightBarButtonItem?.enabled = false
        
        let titleView = UIView(frame: CGRect(x: 0, y: 0, width: 100, height: 40))
        navigationItem.titleView = titleView;
        
        let titleLabel = UILabel(title: "发微博", Color: defaultColor, fontSize: 20, textAlignment: NSTextAlignment.Center)
        let nameLabel = UILabel(title: UserAccountOAuthModel.shared.Account?.name, Color: UIColor.lightGrayColor(), fontSize: 15, textAlignment: NSTextAlignment.Center)
        
        
        titleView.addSubview(titleLabel)
        titleView.addSubview(nameLabel)
        
        nameLabel.snp_makeConstraints { (make) -> Void in
            make.centerX.top.equalTo(titleView)
        }
        titleLabel.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(nameLabel.snp_bottom)
            make.centerX.equalTo(nameLabel)
        }
        
    }
    
    
    private func setTextView() {
        
        textView.delegate = self
        view.backgroundColor = UIColor.lightGrayColor()
        
        view.addSubview(textView)
        textView.addSubview(placeHolderLabel)
       
        textView.snp_makeConstraints { (make) -> Void in
            make.left.top.right.equalTo(self.view)
            make.height.equalTo(DcScreenheight * 0.3)
        }
        
        placeHolderLabel.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(textView).offset(8)
            make.left.equalTo(textView).offset(5)
        }
        
        
    }
    
    private func setToolbar() {
        
        view.addSubview(toolbar)
        
        toolbar.snp_makeConstraints { (make) -> Void in
            make.left.right.bottom.equalTo(self.view)
            make.height.equalTo(44)
        }
        
        let itemSettings = [["imageName": "compose_toolbar_picture","actionName": "selectPicture"],
            ["imageName": "compose_mentionbutton_background"],
            ["imageName": "compose_trendbutton_background"],
            ["imageName": "compose_emoticonbutton_background"],
            ["imageName": "compose_add_background"]]
        
        var itemList = [UIBarButtonItem]()
        
        for dict in itemSettings {
            
            let item = UIBarButtonItem(image: dict["imageName"], target: self, action: dict["actionName"])
    
            itemList.append(item)
            
            let spring = UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil)
            
            itemList.append(spring)
        }
        
        itemList.removeLast()
        
        toolbar.setItems(itemList, animated: true)
    }
    
    
    
    func textViewDidChange(textView: UITextView) {
        
        let hasText = textView.hasText()
        placeHolderLabel.text = hasText ? "" : "分享新鲜事..."
        navigationItem.rightBarButtonItem?.enabled = hasText
    }
}
